package co.edu.eafit.rfp.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CommonFunctions {

	/**
	 * Finds the distance between 2 points with the haversine algorithm
	 * 
	 * @param latitude1
	 * @param longitude1
	 * @param latitude2
	 * @param longitude2
	 * @return
	 */
	public static double getDistanceBetweenPoints(float latitude1,
			float longitude1, float latitude2, float longitude2) {
		return (6371 * Math.acos(Math.cos(Math.toRadians(latitude1))
				* Math.cos(Math.toRadians(latitude2))
				* Math.cos(Math.toRadians(longitude2)
						- Math.toRadians(longitude1))
				+ Math.sin(Math.toRadians(latitude1))
				* Math.sin(Math.toRadians(latitude2))));
	}

	/**
	 * Produces the clause of the Haversine formula. Useful for order by
	 * distance
	 * 
	 * @return
	 */
	public static String getDistanceAlgorithm(String locationsPath,
			float latitude, float longitude) {
		return "( 6371 * acos( cos( radians(" + latitude
				+ ") ) * cos( radians( " + locationsPath
				+ ".latitude ) ) * cos( radians( " + locationsPath
				+ ".longitude ) - " + "radians(" + longitude
				+ ") ) + sin( radians(" + latitude + ") ) * sin( radians( "
				+ locationsPath + ".latitude ) ) ) )";
	}

	/**
	 * Encrypts a text to the MD5 representation
	 * 
	 * @param textToEncrypt
	 *            text to encrypt.
	 * @return
	 */
	public static String encryptToMd5(String textToEncrypt) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// THIS WILL NEVER HAPPEN
		}
		String input = textToEncrypt; // storing the password in input string
		md.update(input.getBytes()); // storing the password in md object as
										// bytes
		byte[] output = md.digest(); // producing the 128 bit output using the
										// md5 algorithm

		return bytesToHex(output); // converting the bytes to
									// string and storing in
									// cipher String
	}

	/**
	 * Converts an array of bytes to the Hexadecimal representation
	 * 
	 * @param b
	 *            array of bytes.
	 * @return
	 */
	public static String bytesToHex(byte[] b) {

		char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		StringBuffer buf = new StringBuffer();
		for (int j = 0; j < b.length; j++) {
			buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
			buf.append(hexDigit[b[j] & 0x0f]);
		}
		return buf.toString();
	}
}
